package com.tosmart.jorm.util;

import java.sql.Connection;

/**
 * Database access helper class
 *
 * @author tosmart@gmail.com
 */
public class DBAssistant extends DBBase {

    /**
     * Constructor
     *
     * @param connection Database Connection
     * @param autoClose  Done, whether to automatically
     *                   close the data connection.
     */
    public DBAssistant(Connection connection, boolean autoClose) {
        super(connection, autoClose);
    }

    /**
     * According to the given conditions, to obtain
     * the number of records in the table.
     *
     * @param table       table name
     * @param whereClause Query conditions
     * @param args        SQL query a list of parameters that need to
     * @return >=0:The number of records to satisfy the conditions
     *         -1:fail
     */
    public long count(
            String table, String whereClause,
            Object... args) {

        StringBuffer sql = new StringBuffer();

        sql.append("SELECT COUNT(*) FROM ");
        sql.append(table).append(' ').append(whereClause);

        return selectLong(sql.toString(), args);
    }

    /**
     * Specified in the table to determine the
     * existence of the records specified conditions
     *
     * @param table       table name
     * @param whereClause Query conditions
     * @param args        SQL query a list of parameters that need to
     * @return In the table records the existence of specified conditions
     */
    public boolean exists(
            String table, String whereClause,
            Object... args) {

        return count(table, whereClause, args) > 0;
    }
}
